package com.aix.demo.activity;

import java.util.Map;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.aix.android.framework.activity.BaseActivity;
import com.aix.demo.R;

public class SharedPreferencesActivity extends BaseActivity {
	
	private TextView mTextView;
	
	private EditText edittext1;
	
	private EditText edittext2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_shared_preferences);
		
		mTextView = (TextView) findViewById(R.id.textview);
		
		final SharedPreferences prefs = getSharedPreferences("test", Activity.MODE_PRIVATE);
		
		showPreferences(prefs);
		
		final SharedPreferences.Editor editor = prefs.edit();
		
		Button btn = (Button) findViewById(R.id.button1);
		edittext1 = (EditText) findViewById(R.id.edittext1);
		edittext2 = (EditText) findViewById(R.id.edittext2);
		btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String key = edittext1.getText().toString();
				String value = edittext2.getText().toString();
				
				editor.putString(key, value);
				editor.commit();
				
				showPreferences(prefs);
			}
		});
	}
	
	private void showPreferences(SharedPreferences prefs) {
		Map<String, ?> map = prefs.getAll();
		boolean first = true;
		for (String k : map.keySet()) {
			String temp = k + " = " + map.get(k);
			if (first) {
				first = false;
				
				mTextView.setText(temp);
			} else {
				mTextView.append("\n" + temp);
			}
		}
	}
}
